package org.intelli.dl.learn.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.intelli.dl.learn.model.common.R;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * @author: Michael
 * @date: 2025/4/22
 * @desc:
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       String s,
                       BlockException e) throws Exception {
        httpServletResponse.setStatus(429); // too many requests
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        PrintWriter printWriter = httpServletResponse.getWriter();

        R r = R.error(500, s + "被Sentinel限制了，原因：" + e.getClass());

        String json = objectMapper.writeValueAsString(r);

        printWriter.write(json);

        printWriter.flush();
        printWriter.close();
    }

}
